<!-- 下拉菜单 -->
<template>
    <div class="dropdown" ref="dropdownRef">
        <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click="toggle">{{ title }}</a>
        <ul class="dropdown-menu" :class="{'show': isShow}">
            <!-- <li><a class="dropdown-item" href="#">新建文章</a></li>
            <li><a class="dropdown-item" href="#">编辑资料</a></li>
            <li><a class="dropdown-item" href="#">退出登录</a></li> -->
            <slot></slot>
        </ul>
    </div>
</template>

<script lang='ts'>
import { defineComponent, ref, onMounted, onUnmounted, watch, watchEffect } from 'vue';
import useClickOutSide from '@/hooks/useClickOutSide'
export default defineComponent({
   name: 'DropDown',
   props: {
       title: {
           type: String,
           require: true,
       }
   },

   setup() {
       const isShow = ref(false);
       const toggle = () => {
           isShow.value = !isShow.value
       }

       // ref dom
       const dropdownRef = ref<HTMLElement | null >(null);
       
    //    // 单击关闭下拉框
    //    const hander = (e: MouseEvent) => {
    //        if(dropdownRef.value) {
    //            // 判断一个节点是否包含子节点
    //            if(!dropdownRef.value.contains(e.target as HTMLElement) && isShow.value) {
    //                isShow.value = false;
    //            }
    //        }
    //    }

    //    onMounted(() => {
    //        console.log("dropdownRef==",dropdownRef.value)
    //        document.addEventListener('click', hander);
    //    })

    //    onUnmounted(() => {
    //        document.removeEventListener('click', hander);
    //    })

        // 抽离单击关闭下拉框
        // const { isClickOutSide } = useClickOutSide(dropdownRef);
        const isClickOutSide  = useClickOutSide(dropdownRef);
        watch(isClickOutSide, () => {
              console.log("watch---isClickOutSide==",isClickOutSide.value);
            if(isClickOutSide.value && isShow.value) {
                isShow.value = false;
            }
        })
        
       return {
           isShow,
           toggle,
           dropdownRef
       }
   },
})
</script>
<style lang='scss' scoped>
</style>